package com.examine.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.sql.DataSource;

import com.google.inject.Inject;

public abstract class BaseData {
	@Inject
	DataSource datasource;

	protected CallableStatement prepareCall(String command) throws SQLException {
		Connection conn = null;
		try {
			conn = datasource.getConnection();
			return conn.prepareCall(command);
		} catch (SQLException e) {
			if (conn != null)
				conn.close();
			throw e;
		}
	}
	
	protected void executeNonQuery(CallableStatement statement) throws SQLException {
		Connection conn=statement.getConnection();
		
		try {
			statement.executeUpdate();
			
			statement.close();
			
		} finally {
			if(conn!=null)
			   conn.close();
		}
	}
	
	protected DataTable executeQuery(CallableStatement statement) throws SQLException {
		Connection conn=statement.getConnection();
		try {
			ResultSet rs = statement.executeQuery();
			ResultSetMetaData metaData = rs.getMetaData();

			int columns = metaData.getColumnCount();
			DataTable dataTable = new DataTable();

			for (int i = 0; i < columns; i++) {
				dataTable.addColumn(metaData.getColumnName(i+1), i);
			}

			while (rs.next()) {

				DataRow row = dataTable.newRow();
				for (int j = 0; j < columns; j++) {
					{
						row.Set(j, rs.getObject(j+1));
					}
				}
			}
			rs.close();
			statement.close();
			
			return dataTable;
		} finally {
			if(conn!=null)
			   conn.close();
		}
	}
}
